package com.wavehi.web;

import com.wavehi.pojo.User;
import com.wavehi.service.IUserService;
import com.wavehi.service.impl.UserServiceImpl;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.util.UUID;

/**
 * @Author WaveHi
 * @Date 26/9/2021 下午 4:57
 * @Version 1.0
 * @Contact HJBWaveHi@163.com
 * @Description Accept the request from user and response to user.
 */
@WebServlet("/userServlet")
@MultipartConfig(maxFileSize = 5 * 1024 * 1024L, maxRequestSize = 5 * 1024 *1024 * 1024L)
public class UserServlet extends BaseServlet{
    //Get the service for user.
    private IUserService ius = new UserServiceImpl();

    /**
     * This method have no sense.
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void base(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    /**
     * Log out.
     */
    protected void cancel(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //Get the cookie for user information
        Object user = req.getSession().getAttribute("user");
        String username = null;
        if(user != null) {
            User upUser = (User)user;
            username = upUser.getUsername();
        }
        Cookie usernameCookie = new Cookie("username", username);
        usernameCookie.setMaxAge(0);
        //Respond cookie to the browser
        resp.addCookie(usernameCookie);
        //Bind the user name to request
        req.setAttribute("username",username);
        //Unbind the user information from session
        req.getSession().removeAttribute("user");
        //Get the dispatcher for login page
        RequestDispatcher rd = req.getRequestDispatcher("/page/user/user_login.jsp");
        //Forward
        rd.forward(req, resp);
    }

    /**
     * Update the user information
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //Get the information for update user
        String username = req.getParameter("username").trim();
        String id = req.getParameter("id");
        String password = req.getParameter("password").trim();
        //Judge
        boolean leadRepeatedUsername =
                !(ius.getUser(Long.parseLong(id)).getUsername().equals(username) && ius.userExists(username));
        if(leadRepeatedUsername) {
            //Bind the error message and user information to request
            req.setAttribute("errorMsg", "User name already have exist!");
            req.setAttribute("user", new User(Long.parseLong(id), username, password, null));
            //Get the dispatcher for update page
            RequestDispatcher rd = req.getRequestDispatcher("/page/user/user_edit.jsp");
            //Forward
            rd.forward(req, resp);
            return;
        }
        //Save the information to database
        Part headImage = req.getPart("headImage");
        String realPath = req.getServletContext().getRealPath("/static/image/user_headImage/");
        String fileName = UUID.randomUUID()
                + headImage.getSubmittedFileName().substring(headImage.getSubmittedFileName().lastIndexOf("."));
        headImage.write(realPath + fileName);
        User user =
                new User(Long.parseLong(id), username, password, "/static/image/user_headImage/" + fileName);
        ius.updateUser(user);
        //Bind the new information to session
        req.getSession().setAttribute("user", user);
        //Get the new cookie for user name
        Cookie usernameCookie = new Cookie("username", username);
        usernameCookie.setMaxAge(60 * 60 * 24 * 7);
        //Respond cookie to browser
        resp.addCookie(usernameCookie);
        //Get the dispatcher for index page
        RequestDispatcher rd = req.getRequestDispatcher("/page/user/user_login_success.jsp");
        //Forward
        rd.forward(req, resp);
    }

    /**
     * Get the user information for update.
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void getUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //Get the user information
        Object user = req.getSession().getAttribute("user");
        //Bind the user information to request
        req.setAttribute("user", user);
        //Get dispatcher for update page
        RequestDispatcher rd = req.getRequestDispatcher("/page/user/user_edit.jsp");
        //Forward
        rd.forward(req, resp);
    }

    /**
     * Deal the information for user login
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //Get the information of user
        String username = req.getParameter("username").trim();
        String password = req.getParameter("password").trim();
        //Judge whether user exists.
        boolean exist = ius.userExists(username, password);
        if(!exist) {
            //Bind the error message and information of user to request
            req.setAttribute("errorMsg", "User name or password is incorrect!");
            req.setAttribute("username", username);
            //Get the dispatcher for login page
            RequestDispatcher rd = req.getRequestDispatcher("/page/user/user_login.jsp");
            //Forward
            rd.forward(req, resp);
            return;
        }
        //Bind the user information to session
        req.getSession().setAttribute("user", ius.getUser(username));
        //Get the cookie for user name
        Cookie usernameCookie = new Cookie("username", username);
        usernameCookie.setMaxAge(60 * 60 * 24 * 7);
        //Respond cookie to browser
        resp.addCookie(usernameCookie);
        //Get dispatcher
        RequestDispatcher rd = req.getRequestDispatcher("/page/user/user_login_success.jsp");
        //Forward
        rd.forward(req, resp);
    }


    /**
     * Deal the information for user register.
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void register(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //Get the information of user
        String username = req.getParameter("username").trim();
        //Judge whether user name exists
        boolean exist = ius.userExists(username);
        if(exist) {
            //Bind the error message and information of user to request
            req.setAttribute("errorMsg", "User name already have existed.");
            req.setAttribute("username", username);
            //Get dispatcher
            RequestDispatcher rd = req.getRequestDispatcher("/page/user/user_register.jsp");
            //Forward
            rd.forward(req, resp);
            return;
        }
        String password = req.getParameter("password");
        //Get the part of headImage
        Part headImage = req.getPart("headImage");
        String submittedFileName = headImage.getSubmittedFileName();
        String realDir = req.getServletContext().getRealPath("/static/image/user_headImage/");
        String fileName = UUID.randomUUID() + submittedFileName.substring(submittedFileName.lastIndexOf("."));
        headImage.write(realDir + fileName);
        //Encapsulates the user information
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setImagePath("/static/image/user_headImage/" + fileName);
        //Save the user information to database
        ius.addUser(user);
        //Bind the user information to session
        req.getSession().setAttribute("user", ius.getUser(username));
        //Get cookie for user information
        Cookie usernameCookie = new Cookie("username", username);
        usernameCookie.setMaxAge(60 * 60 * 24 * 7);
        //Respond cookie to browser.
        resp.addCookie(usernameCookie);
        //Get the dispatcher
        RequestDispatcher rd = req.getRequestDispatcher("/page/user/user_login_success.jsp");
        //Forward
        rd.forward(req, resp);
    }
}
